#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "usage: " << argv[0] << " ip port " << std::endl;
    }

    // 1. sock
    int sockId = socket(AF_INET, SOCK_STREAM, 0);
    if (sockId < 0)
    {
        std::cout << "socket error" << std::endl;
    }
    // 2. connect
    struct sockaddr_in seraddr;
    memset(&seraddr, 0, sizeof(seraddr));
    seraddr.sin_family = AF_INET;
    seraddr.sin_addr.s_addr = inet_addr(argv[1]);
    seraddr.sin_port = htons(atoi(argv[2]));

    connect(sockId, (struct sockaddr *)&seraddr, sizeof(seraddr)); // 连接服务器并且隐式bind

    while (true)
    {
        // 3. send / write
        std::string message;
        getline(std::cin, message);
        int s = send(sockId, message.c_str(), message.size(), 0);

        if(s > 0)
        {
            // 4. recv / read
            char buffer[1024];
            int rs = recv(sockId, buffer, sizeof(buffer) - 1, 0);
            if(rs > 0)
            {
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "server closed" << std::endl;
                exit(2);
            }
        }
    }

    return 0;
}